import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent, STData } from '@delon/abc/st';
import { SFDateWidgetSchema, SFSchemaEnum, SFSelectWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TaxManagementService } from '../../services/tax-management.service';
import { TaxManagementUploadSettingComponent } from './upload-setting/upload-setting.component';
import { TaxManagementOrderVerifyResultComponent } from './verify-result/verify-result.component';
import { NzImageService } from 'ng-zorro-antd/image';
import { image } from 'html2canvas/dist/types/css/types/image';

@Component({
  selector: 'app-tax-management-order-reporting',
  templateUrl: './order-reporting.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class TaxManagementOrderReportingComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];
  tabType!: string;
  isLoading: boolean = false;
  tabs: any[] = [
    { name: '待上传', value: '0' },
    { name: '上传中', value: '3' },
    { name: '已上传', value: '1' },
    { name: '异常', value: '2' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '0'; //选择的项目
  serviceTel = '';
  constructor(
    public service: TaxManagementService,
    private router: Router,
    private ar: ActivatedRoute,
    private modal: NzModalService,
    public searchDrawerService: SearchDrawerService,
    public imageService: NzImageService
  ) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {}, {
      putStatus: this.selectedIndex
    });
    delete params._$expand;
    return { ...params };
  }

  /**
   * 选中行
   */
  get selectedRows() {
    return this.st?.list.filter((item: any) => item.checked) || [];
  }

  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: { title: '订单号', type: 'string', ui: { placeholder: '请输入' } },
        wayBillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        shipperId: {
          type: 'string',
          title: '货主',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            }
          } as SFSelectWidgetSchema
        },
        driverName: {
          title: '承运司机',
          type: 'string',
          ui: {
            placeholder: '请输入司机姓名/手机号'
          }
        },
        carNo: {
          title: '车牌号',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入'
          }
        },
        collectionUserName: {
          title: '收款人',
          type: 'string',
          maxLength: 9,
          ui: {
            placeholder: '请输入'
          }
        },
        // putStatus: {
        //   title: '上传状态',
        //   type: 'string',
        //   enum: [
        //     {label: '待上传',value: 0},
        //     {label: '已上传',value: 1},
        //     {label: '上传异常',value: 2},
        //   ],
        //   ui: {
        //     widget:'select',
        //     placeholder: '请选择',
        //     visibleIf: {
        //       _$expand: (value: boolean) => value,
        //     },
        //   }
        // },
        checkStatus: {
          title: '本地校验',
          type: 'string',
          enum: [
            { label: '校验中', value: 0 },
            { label: '通过', value: 1 },
            { label: '不通过', value: 2 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        },
        recentlyPutTime: {
          title: '上传时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        orderPayTime: {
          title: '结束时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        }
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '上传状态', render: 'putStatus', className: 'text-center', width: '120px' },
      { title: '异常信息', index: 'exceptionInfo', className: 'text-center', width: '200px' },
      { title: '本地校验', render: 'checkStatus', className: 'text-center', width: '120px' },
      {
        title: '订单号',
        index: 'billCode',
        className: 'text-center',
        width: '150px'
      },
      { title: '运单号', index: 'wayBillCode', className: 'text-center', width: '150px' },
      {
        title: '网络货运人',
        index: 'networkTransporterName',
        className: 'text-center',
        width: '180px'
      },
      {
        title: '档案编号',
        index: 'archivesNo',
        className: 'text-center',
        width: '180px'
      },
      {
        title: '品牌型号',
        index: 'carBrand',
        className: 'text-center',
        width: '180px'
      },
      { title: '装货地', index: 'loadingAddress', render: 'loadingPlace', className: 'text-center', width: '200px' },
      { title: '装货地详细地址', index: 'loadingDetailedAddress', render: 'loadingPlace', className: 'text-center', width: '200px' },
      { title: '卸货地', index: 'unloadAddress', render: 'dischargePlace', className: 'text-center', width: '120px' },
      { title: '卸货地详细地址', index: 'unloadDetailedAddress', className: 'text-center', width: '180px' },
      { title: '货主名称', index: 'shipperName', className: 'text-center', width: '180px' },
      { title: '货主纳税人识别号', index: 'shipperProvinceCode', className: 'text-center', width: '180px' },
      { title: '录单时间', index: 'billCreateTime', className: 'text-center', width: '250px' },
      { title: '接单时间', index: 'wayBillCreateTime', className: 'text-center', width: '200px' },
      { title: '发车时间', index: 'loadTime', className: 'text-center', width: '200px' },
      { title: '到车时间', index: 'unloadTime', className: 'text-center', width: '150px' },
      { title: '结束时间', index: 'orderPayTime', className: 'text-center', width: '150px' },
      { title: '订单金额', render: 'orderAmount', className: 'text-center', width: '120px' },
      { title: '司机姓名', render: 'driverName', className: 'text-center', width: '150px' },
      { title: '司机身份证号', index: 'driverCertificateNumber', className: 'text-center', width: '180px' },
      { title: '车牌号', index: 'carNo', className: 'text-center', width: '100px' },
      { title: '货物信息', render: 'goodsName', className: 'text-center', width: '200px' },
      { title: '运费金额', render: 'wayAmount', className: 'text-center', width: '100px' },
      { title: '装卸方式', index: 'loadingUnloadWay', className: 'text-center', width: '180px' },
      { title: '支付方式', index: 'payMent', className: 'text-center', width: '150px' },
      { title: '支付账号', index: 'paymentAccount', className: 'text-center', width: '200px' },
      { title: '银行流水号', index: 'bankSerialNumber', className: 'text-center', width: '150px' },
      { title: '收款人姓名', index: 'collectionUserName', className: 'text-center', width: '250px' },
      { title: '收款人身份证号码', index: 'collectionUserCertificateNumber', className: 'text-center', width: '180px' },
      { title: '装货照片', render: 'loadingPicture', className: 'text-center', width: '100px' },
      { title: '卸货照片', render: 'unloadPicture', className: 'text-center', width: '100px' },
      { title: '提货单', render: 'loadingLadingBill', className: 'text-center', width: '100px' },
      { title: '签收单', render: 'signatureForm', className: 'text-center', width: '100px' },
      { title: '上传次数', index: 'putNumber', className: 'text-center', width: '100px' },
      { title: '最近上传时间', index: 'recentlyPutTime', className: 'text-center', width: '180px' }
    ];
  }

  /**
   *撤回
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要撤回的数据');
      return;
    }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.modal.confirm({
      nzTitle: '撤回提示',
      nzContent: ' 撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_get_recessionTaxOrder, params).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }
  /**
   *撤销
   * @param record 记录实例
   */
  resetData() {
    let params: any = {};
    if (this.selectedRows.length === 0) {
      params = {};
    } else {
      params = [];
      this.selectedRows.forEach(item => {
        params.push(item.billId);
      });
    }

    this.service.request(this.service.$api_get_renewalOrderById, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('更新成功');
        this.st.load(1);
      }
    });
  }
  /**
   *撤销
   * @param record 记录实例
   */
  unnormal(value: any) {
    // if (this.selectedRows.length === 0) {
    //   this.openWainingModal('请选择需要更新的数据！');
    //   return;
    // }
    console.log(this.selectedRows);
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.modal.confirm({
      nzTitle: '税务审核结果',
      nzContent: `${value?.exceptionInfo}`,
      nzOkText: '确定',
      nzCancelText: '',
      nzOnOk: () => {
        this.service.request(this.service.$api_get_recessionTaxOrder, params).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }

  selectChange(item: any) {
    console.log(item);

    this.selectedIndex = item?.value || '';
    setTimeout(() => {
      this.st.load();
    });
  }

  /**
   * 查看当行数据
   */
  view(record: STData) {
    // this.router.navigate(['../view', record.uuid], { relativeTo: this.ar });
    this.router.navigate(['../detail'], {
      queryParams: {
        id: record.id
      },
      relativeTo: this.ar
    });
  }

  // appeal(item: any) {
  //   const modalRef = this.modal.create({
  //     nzTitle: '申诉',
  //     nzWidth: '40%',
  //     nzContent: CtcAppealComponent,
  //     nzComponentParams: {
  //       i: item,
  //       status: 'add'
  //     },
  //     nzFooter: null
  //   });
  //   modalRef.afterClose.subscribe(res => {
  //     if (res) {
  //       this.search({ representationsStatus: '' });
  //     }
  //   })
  // }

  /**
   * 上传
   */
  upload() {
    let status = false;
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要上传的数据');
      return;
    }
    this.selectedRows.forEach(item => {
      if (item?.putStatus != '0') {
        status = true;
      }
    });
    if (status) {
      this.service.msgSrv.warning('选择了已上传，请重新勾选！');
      return;
    }

    // if(this.selectedRows.find(item => item.checkStatus !== 1)) {
    //   this.service.msgSrv.warning('选择了未通过校验的订单，请重新勾选！');
    //   return;
    // }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.service.request(this.service.$api_get_uploadingTaxOrder, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('上传成功');
        this.st.load();
      }
    });
  }

  /**
   *
   * @param params 上传设置
   */
  uploadSetting() {
    const modalRef = this.modal.create({
      nzTitle: '税务上传设置',
      nzWidth: 600,
      nzContent: TaxManagementUploadSettingComponent,
      nzComponentParams: {},
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  /**
   * 查看校验结果
   */
  viewResult(item: any) {
    const modalRef = this.modal.create({
      nzTitle: '本地校验结果',
      nzWidth: 1200,
      nzNoAnimation: true,
      nzContent: TaxManagementOrderVerifyResultComponent,
      nzComponentParams: {
        record: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    if (record?.billStatus !== '2') {
      return;
    }
    this.openWainingModal('监管审核结果', record?.result);
  }

  search() {
    this.st.load(1);
  }

  /**
   * 异步导出
   */
  export() {
    this.service.exportStart(
      { ...this.reqParams, pageSize: -1, putStatus: this.selectedIndex },
      this.service.$api_async_export_order_reporting_list
    );
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content
    });
  }

  viewPhoto(images: any[]) {
    if (images.length > 0) {
      const imgs = images.map(item => ({ src: item }));
      this.imageService.preview(imgs);
    }
  }

  exportList() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_getTaxOrderPage_page_export);
  }
}
